const fs = require('fs')
const path = require('path')
const express = require('express')
const router = express.Router()
const AcModel = require('../../models/ac')
const EpModel = require('../../models/ep')
const PlayModel = require('../../models/play')
const CommentModel = require('../../models/comments')
const tagModel = require('../../models/tag')
const checkLogin = require('../../middlewares/check').checkLogin
const Ac = require('../../lib/mongo').Ac

// GET /anime 所有用户或者特定用户的文章页
//   eg: GET /anime?author=xxx
router.get('/', function(req, res, next) {
  const author = req.query.author
  const limit = 2
  let page = Number(req.query.p || 1)
  let pageSize = 0

  Ac.count()
    .then(count => {
      // 计算总页数
      pageSize = Math.ceil(count / limit)
      // 取值不能超过 pageSize
      page = Math.min(page, pageSize)
      // 取值不能小于1
      page = Math.max(page, 1)
      const skip = (page - 1) * limit
      const pager = {}
      pager.pagePath = '/anime?'
      pager.pageCurrent = page
      pager.maxNum = count // 总条数
      pager.pageCount = pageSize // 计算总页数
      AcModel.getPosts(author, limit, skip)
        .then(function(posts) {
          res.render('ac/index', {
            posts,
            pager,
            count
          })
        })
        .catch(next)
    })
    .catch(next)
})

// POST /anime/create
router.post('/create', checkLogin, function(req, res, next) {
  const author = req.session.user._id
  const pic = req.files.pic.path.split(path.sep).pop()
  const { title, cname, celebrity, original, content, tags } = req.fields

  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
    if (!content.length) {
      throw new Error('请填写内容')
    }
    if (!req.files.pic.name) {
      throw new Error('缺少封面')
    }
  } catch (e) {
    // 注册失败，异步删除上传的头像
    fs.unlink(req.files.pic.path)
    req.flash('error', e.message)
    return res.redirect('back')
  }

  let post = {
    author,
    title,
    cname,
    tags,
    pic,
    content,
    celebrity,
    original
  }

  AcModel.create(post)
    .then(function(result) {
      // 此 post 是插入 mongodb 后的值，包含 _id
      post = result.ops[0]
      req.flash('success', '发表成功')
      // 发表成功后跳转到该文章页
      res.redirect(`/anime/${post._id}`)
    })
    .catch(function(e) {
      // 注册失败，异步删除上传的头像
      fs.unlink(req.files.pic.path)
      next(e)
    })
})

// GET /anime/create 发表动漫
router.get('/create', checkLogin, function(req, res, next) {
  res.render('ac/add')
})

// GET /anime/:acId 单独一篇的文章页
router.get('/:acId', function(req, res, next) {
  const acId = req.params.acId

  Promise.all([
    AcModel.getPostById(acId), // 获取文章信息
    CommentModel.getComments(acId), // 获取该文章所有留言
    EpModel.getEp(acId),
    tagModel.getTag(acId), // 获取该文章所有tag
    AcModel.incPv(acId) // pv 加 1
  ]).then(result => {
    const post = result[0]
    const comments = result[1]
    const list = result[2]
    const tags = result[3]

    const promises = []
    comments.forEach((elm, index) => {
      promises.push(
        CommentModel.getCommentReplys(elm._id).then(function(data) {
          comments[index].subComment = data
        })
      )
    })

    Promise.all(promises).then(() => {
      if (!post) {
        throw new Error('该文章不存在')
      }
      res.send({
        acId,
        post,
        comments,
        list,
        tags,
        postId: acId,
        typeId: 2
      })
    })
  })
})

// GET /anmie/:acId 单独一篇的所有评论
router.get('/:acId/comments', function(req, res, next) {
  const acId = req.params.acId

  Promise.all([
    AcModel.getPostById(acId), // 获取文章信息
    CommentModel.getComments(acId) // 获取该文章所有留言
  ])
    .then(result => {
      const post = result[0]
      const comments = result[1]

      const promises = []
      comments.forEach((elm, index) => {
        promises.push(
          CommentModel.getCommentReplys(elm._id).then(function(data) {
            comments[index].subComment = data
          })
        )
      })

      Promise.all(promises)
        .then(() => {
          if (!post) {
            throw new Error('该文章不存在')
          }
          res.render('ac/comments', {
            acId,
            post,
            comments,
            postId: acId,
            typeId: 2
          })
        })
        .catch(next)
    })
    .catch(next)
})

// GET /anime/:acId/remove 删除一篇文章
router.get('/:acId/remove', checkLogin, function(req, res, next) {
  const acId = req.params.acId
  const author = req.session.user._id
  const typeId = req.query.typeId

  AcModel.getRawAcById(acId).then(function(ac) {
    if (!ac) {
      throw new Error('动漫不存在')
    }
    if (ac.author._id.toString() !== author.toString()) {
      throw new Error('没有权限')
    }
    AcModel.delAcById(acId, typeId)
      .then(function() {
        req.flash('success', '删除成功')
        // 删除成功后跳转到主页
        res.redirect('/anime')
      })
      .catch(next)
  })
})

// GET /anime/:acId/edit 更新AC
router.get('/:acId/edit', checkLogin, function(req, res, next) {
  const acId = req.params.acId
  const author = req.session.user._id

  AcModel.getRawAcById(acId)
    .then(function(ac) {
      if (!ac) {
        throw new Error('该动漫不存在')
      }
      if (author.toString() !== ac.author._id.toString()) {
        throw new Error('权限不足')
      }
      res.render('ac/edit', {
        ac: ac
      })
    })
    .catch(next)
})

// POST /anime/:acId/edit 更新一篇文章
router.post('/:acId/edit', checkLogin, function(req, res, next) {
  const file = req.files.pic.path.split(path.sep).pop()
  const findType = file.indexOf('jpg') !== -1 || file.indexOf('gif') !== -1 || file.indexOf('png') !== -1
  const author = req.session.user._id
  const acId = req.params.acId
  const pic = findType ? file : req.fields.editpic
  const { title, cname, tags, celebrity, original, content } = req.fields

  if (!findType) {
    fs.unlink(req.files.pic.path)
  }
  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
    if (!content.length) {
      throw new Error('请填写内容')
    }
    if (!req.files.pic.name && !req.fields.editpic) {
      throw new Error('缺少封面')
    }
  } catch (e) {
    // 注册失败，异步删除上传的文件
    fs.unlink(req.files.pic.path)
    req.flash('error', e.message)
    return res.redirect('back')
  }

  let post = {
    author,
    title,
    pic,
    content,
    celebrity,
    cname,
    tags,
    original
  }

  AcModel.getRawAcById(acId).then(function(ac) {
    if (!ac) {
      throw new Error('该动漫不存在')
    }
    if (author.toString() !== ac.author._id.toString()) {
      throw new Error('权限不足')
    }
    AcModel.updateAcById(acId, post)
      .then(function() {
        req.flash('success', '编辑文章成功')
        // 编辑成功后跳转到上一页
        res.redirect(`/anime/${acId}`)
      })
      .catch(function(e) {
        // 注册失败，异步删除上传的头像
        fs.unlink(req.files.pic.path)
        next(e)
      })
  })
})

// GET /anime/:acId/ep
router.get('/:acId/ep', checkLogin, function(req, res, next) {
  res.render('ac/ep/add')
})

// POST /anime/:acId/ep 创建一集
router.post('/:acId/ep', checkLogin, function(req, res, next) {
  const file = req.files.pic.path.split(path.sep).pop()
  const findType = file.indexOf('jpg') !== -1 || file.indexOf('gif') !== -1 || file.indexOf('png') !== -1
  const author = req.session.user._id
  const acId = req.params.acId
  const pic = findType ? file : ''
  const { title, subTitle, tags, url, source, sort, content } = req.fields

  if (!findType) {
    fs.unlink(req.files.pic.path)
  }
  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
  } catch (e) {
    req.flash('error', e.message)
    // return res.redirect('back')
  }

  const ep = { author, acId, title, subTitle, pic, url, tags, source, content, sort: parseInt(sort) }
  EpModel.create(ep)
    .then(function(result) {
      const post = result.ops[0]
      req.flash('success', '添加成功')
      const play = { author, acId, title, url, subTitle, tags, source, epId: post._id, sort: parseInt(sort) }
      PlayModel.create(play)
      // 发表成功后跳转到该文章页
      res.redirect(`/ep/${post._id}`)
    })
    .catch(next)
})

// GET /anime/:acId/ep/:epId/play
router.get('/:acId/ep/:epId/play', checkLogin, function(req, res, next) {
  res.render('ac/play/add')
})

// POST /anime/:acId/ep/:epId/play 创建一集
router.post('/:acId/ep/:epId/play', checkLogin, function(req, res, next) {
  const author = req.session.user._id
  const { epId, acId } = req.params
  const { title, subTitle, url, tags, source, sort } = req.fields

  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题')
    }
  } catch (e) {
    req.flash('error', e.message)
    return res.redirect('back')
  }

  const play = { author, acId, epId, title, subTitle, url, tags, source, sort: parseInt(sort) }

  PlayModel.create(play)
    .then(function(result) {
      const post = result.ops[0]
      req.flash('success', '添加成功')
      // 发表成功后跳转到该文章页
      res.redirect(`/ep/${post.epId}`)
    })
    .catch(next)
})

module.exports = router
